package com.bestcem.xm.txtanls.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * python答卷分表，分表字段varchar类型的project_id
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/4/19 15:14
 */
@Slf4j
public class SurveyRespondentTableShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        if (availableTargetNames.isEmpty()) {
            throw new UnsupportedOperationException("actual-data-nodes is not support, please check your config");
        }
        // python取ObjectId前两位和后三位拼接成5位字符串，然后对1024取余(模1024，实际上只有后3个字符会起作用)，将余数除以16后获取商作为分表序号
        String index = shardingValue.getValue().substring(shardingValue.getValue().length() - 3);
        int databaseIndex = ((Integer.parseInt(index, 16)) & 1023) >>> 4;
        // 数据库中对应的真实表
        String realTableName = shardingValue.getLogicTableName() + databaseIndex;
        if (availableTargetNames.contains(realTableName)) {
            return realTableName;
        }
        throw new UnsupportedOperationException("route " + realTableName + " is not support, please check your config");
    }
}
